<template>
  <header class="header">
    <div class="header-left">
      <img src="/public/img/logo.png" alt="Logo" class="logo" />
    </div>
    <div :class="{ 'modal': true, 'show': showModal }">
      <div class="modal-content">
        <span class="close-btn" @click="toggleFilter">×</span>
        <el-menu default-active="2" class="custom-menu">
          <el-sub-menu index="1">
            <template #title>
              <el-icon><Menu /></el-icon>
              <span>平台</span>
            </template>
            <el-menu-item 
              index="1-1" 
              @click="handleFilterClick('平台', 'Nintendo')" 
              :class="{ 'selected-filter': isSelected('平台', 'Nintendo') }">
              Nintendo
            </el-menu-item>
            <el-menu-item 
              index="1-2" 
              @click="handleFilterClick('平台', 'Playstation')" 
              :class="{ 'selected-filter': isSelected('平台', 'Playstation') }">
              Playstation
            </el-menu-item>
            <el-menu-item 
              index="1-3" 
              @click="handleFilterClick('平台', 'XBox')" 
              :class="{ 'selected-filter': isSelected('平台', 'XBox') }">
              XBox
            </el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="2">
            <template #title>
              <el-icon><Grid /></el-icon>
              <span>分类</span>
            </template>
            <el-menu-item 
              v-for="category in categories" 
              :key="category.id" 
              :index="'2-' + category.id"
              @click="handleFilterClick('分类', category.id.toString())"
              :class="{ 'selected-filter': isSelected('分类', category.id.toString()) }">
              {{ category.name }}
            </el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="3">
            <template #title>
              <el-icon><Sort /></el-icon>
              <span>排序</span>
            </template>
            <el-menu-item 
              index="3-1" 
              @click="handleFilterClick('排序', '时间顺序')" 
              :class="{ 'selected-filter': isSelected('排序', '时间顺序') }">
              时间顺序
            </el-menu-item>
            <el-menu-item 
              index="3-2" 
              @click="handleFilterClick('排序', '时间倒序')" 
              :class="{ 'selected-filter': isSelected('排序', '时间倒序') }">
              时间倒序
            </el-menu-item>
            <el-menu-item 
              index="3-3" 
              @click="handleFilterClick('排序', '从高到低')" 
              :class="{ 'selected-filter': isSelected('排序', '从高到低') }">
              价格从高到低
            </el-menu-item>
            <el-menu-item 
              index="3-4" 
              @click="handleFilterClick('排序', '从低到高')" 
              :class="{ 'selected-filter': isSelected('排序', '从低到高') }">
              价格从低到高
            </el-menu-item>
          </el-sub-menu>
          <el-menu-item index="confirm" class="confirm-button-item">
            <button @click="confirmFilters" class="confirm-button">确认</button>
          </el-menu-item>
        </el-menu>
      </div>
    </div>
    <div class="header-center">
      <a href="/" class="highlight-link">首页</a>
      <a href="#" class="highlight-link" @click="toggleFilter">筛选</a>
      <a href="/" class="highlight-link" @click="showAboutAndPreventDefault">关于</a>
      <a href="#" class="highlight-link"></a>
      <div class="search-container">
        <input v-model="searchByname" type="text" placeholder="搜索..." class="search-bar" />
        <button class="search-button" @click="handleSearch">搜索</button>
      </div>
    </div>
    <div class="header-right">
      <div class="avatar" @click="handleAvatarClick">
        <template v-if="token">
          <img :src="avatarUrl" class="avatar-img" />
        </template>
        <template v-else>
          <button @click="gotoLogin" class="login-button">登录</button>
        </template>
      </div>
      <div class="clickicon-div" @click="goToMessage">
        <el-icon><Message /></el-icon>
        <div v-if="unreadCount > 0" class="unread-count">{{ unreadCount }}</div>
      </div>
      <div class="clickicon-div" @click="gotoCar">
        <el-icon><ShoppingCart /></el-icon>
      </div>
      <button class="orange-button" @click="goToRelease">发布</button>
    </div>
  </header>

  <div v-if="ShowAbout" class="about-modal">
    <div class="about-content">
      <span class="close-about-btn" @click="ShowAbout = false">×</span>
      <p class="about-diejia">
        <h2 class="about-title">你好,非常感谢你的访问</h2>
        这个项目是学生求职做的练习项目,没有做并发,异步等场景的优化和调试。请不要对它进行多次高频繁的访问
        <br>
        <br>
        有关上传图片的功能,都是需要通过阿里的oss实例来实现的,如果超过了流量,可能就要额外掏钱了。所以测试功能请不要上传过多图片
        <br>
        <br>
        项目用到的所有图片资源来自网络的仅作为非盈利展示用途,侵删
        <br>
        <br>
        另外,这个项目肯定还要很多不完整的地方和Bug。请各路大神高抬贵手。该项目为非盈利项目,内容已标明出处。
        <img src="/public/img/gtgs.png" class="responsive-img">
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref ,onMounted,onUnmounted} from 'vue';
import { defineProps } from 'vue';
import axios from 'axios';
import { Menu, Grid, Sort } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import '../css/header.css'
import '../css/query.css'

const showModal = ref(false);
const ShowAbout = ref(false);

const token = localStorage.getItem('token');
const loginId = Number(localStorage.getItem('userId'))
const router = useRouter();
const avatarPath = localStorage.getItem('avatarPath');
const avatarUrl = ref<string>(avatarPath ?? ''); // 如果 avatarPath 是 null，则使用空字符串

const searchByname = ref('');

interface Category {
  id: number;
  name: string;
}

const categories = ref<Category[]>([]);
const selectedFilters = ref<{ type: string; value: string }[]>([]);

const getCategoriesLink = "http://localhost:8080/common/getCategories";
const getUnReadLink = "http://localhost:8080/message/getUnRead";

const unreadCount = ref<number>(0);


const getCategories = async () => {
  try {
    const response = await axios.get(getCategoriesLink);
    categories.value = response.data.data;
  } catch (error) {
    console.error('Failed to fetch categories:', error);
  }
};

const toggleFilter = () => {
  showModal.value = !showModal.value;
};

const handleFilterClick = (type: string, value: string) => {
  const index = selectedFilters.value.findIndex(filter => filter.type === type && filter.value === value);
  if (index !== -1) {
    selectedFilters.value.splice(index, 1);
  } else {
    selectedFilters.value = selectedFilters.value.filter(filter => filter.type !== type);
    selectedFilters.value.push({ type, value });
  }
};

const isSelected = (type: string, value: string) => {
  return selectedFilters.value.some(filter => filter.type === type && filter.value === value);
};

import CryptoJS from 'crypto-js';

const encryptParameters = (parameters: any) => {
  const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(parameters), 'secret key').toString();
  return ciphertext;
};

const confirmFilters = () => {
  const filterObject = {
    name: searchByname.value,
    platform: selectedFilters.value.find(filter => filter.type === '平台')?.value || '',
    sortType: selectedFilters.value.find(filter => filter.type === '排序')?.value || '',
    categoriesId: parseInt(selectedFilters.value.find(filter => filter.type === '分类')?.value || '0')
  };

  // 加密参数
  const encryptedParams = encryptParameters(filterObject);

  router.push({ 
    path: '/search', 
    query: {
      params: encryptedParams  // 发送加密后的参数
    }
  });
  showModal.value = false;
};

const gotoLogin = async () => {
  const response = await axios.get('http://localhost:8080/user/toLogin');
  router.push({ name: response.data });
};

const showAboutAndPreventDefault = (event: Event) => {
  event.preventDefault(); // 阻止默认跳转行为
  showAbout(); // 调用原有的 showAbout 方法
};
const showAbout = () =>{
  ShowAbout.value=true
}

const handleAvatarClick = () => {
  if (token) {
    router.push({ name: 'UserInfo' });
  }
};

const handleSearch = () => {
  const filterObject = {
    name: searchByname.value,
    platform: selectedFilters.value.find(filter => filter.type === '平台')?.value || '',
    sortType: selectedFilters.value.find(filter => filter.type === '排序')?.value || '',
    categoriesId: parseInt(selectedFilters.value.find(filter => filter.type === '分类')?.value || '0')
  };
  // 加密参数
  const encryptedParams = encryptParameters(filterObject);
  router.push({ 
    path: '/search', 
    query: {
      params: encryptedParams  // 发送加密后的参数
    }
  });
};

const gotoCar=()=>{
  if (token) {
    router.push({ name: 'SuppingCar' });
  }else{
    router.push({ name: 'Login' });
  }
}

const goToMessage=()=>{
  if (token) {
    router.push({ name: 'MessageNoId' });
  }else{
    router.push({ name: 'Login' });
  }
}

// 获取未读的消息的数量
const getUnRead = async (id:number|null) => {
  if (id===null){
    id=0
  }
  try {
    const response = await axios.post(getUnReadLink, loginId, {
      headers: {
        'Content-Type': 'application/json',
      },
    })
    if (response.data.state && response.data.data !== 0) {
      unreadCount.value = response.data.data;
    }else{
      unreadCount.value=0;
    }
  } catch (error: unknown) {
    console.error('获取回复消息失败: ' + (error as Error).message)
  }
}

const startPolling = () => {
  const interval = setInterval(() => {
    if (loginId) {
      getUnRead(loginId);
    }
  }, 1000); // 每1秒轮询一次

  onUnmounted(() => {
    clearInterval(interval);
  });
};

const goToRelease =()=>{
  router.push({ name: 'Release' });
}

defineProps<{
  getGoods: (filterObject: { name: string; platform: string; sortType: string; categoriesId: number }) => void;
}>();

onMounted(() => {
  getCategories();
  startPolling();
});
</script>

